<?php
class Clu_Controller_Action_Hvn extends Zend_Controller_Action 
{
    public $db;
    public $holderWeights;
    public $regionId;
    public $boxWeight;
    
    public function init()
    {
        $this->db = Zend_Db_Table::getDefaultAdapter(); //TODO: Remove this when the Models are fine
        //$this->holderWeights = Zend_Registry::get('holderWeights');
        $this->regionId = 4;
        $this->boxWeight = 1;
    }
    
    /**
     * TODO: if development mode then use the default behaviour
     * 
     * @param 
     */
    
    public function preDispatch()
    {
    	$module = $this->_request->getModuleName();
    	$incomingRequest = $module . '/' .$this->_request->getControllerName() .'/'.$this->_request->getActionName();
//		Zend_Registry::get('logger')->log("-------- Clu_Controller_ACTION_HVN.predispatch : " . $incomingRequest, Zend_Log::INFO);

		$sess = new Zend_Session_Namespace(CLU_NS);
//		die($incomingRequest);
		//save this for block->finalAction to generate templates and such...
    	if (!isset($sess->incomingRequest))
    	{
    		$sess->incomingRequest = $incomingRequest;
    		$tmp = explode('/', $incomingRequest);
	    	if (in_array($tmp[0], array("place", "event", "tour", "home")))
    			$this->view->placeholder('currentPage')->set($tmp[0]);
    		else
    			$this->view->placeholder('currentPage')->set("undefinedddd");
    		
    	}	 
    	$this->regionId = $this->_request->getParam('hvnRegionId', 4);
    	$this->boxWeight = $this->_request->getParam('hvnBoxWeight', 1);
    	if ($this->_request->getControllerName() == 'ajax')
    	{
    		//$referrer = $_SERVER['HTTP_REFERER'];//http://hvn/en/article/index/new
    		//
    		//die_a($_SERVER);
	    	//TODO: make sure the REFERRER_IP is same as herevietnam.vn for all the
    		//ajax request
    		//this is still not enough of security
    	}
    }
    
    public function postDispatch()
    {
    	//$msg = "action.hvn.postDispatch : " . $this->_request->getModuleName() . '/' .$this->_request->getControllerName() .'/'.$this->_request->getActionName(); 
		//Zend_Registry::get('logger')->log($msg, Zend_Log::INFO);    
        //asort($this->holderWeights); moved to dispatchLoopShutdown()

		//Zend_Registry::set('holderWeights', $this->holderWeights);
		//unset($this->view);
		
		//now invoke the block module if necessary
		//only invoke if this action is the last on the stack
		if (count ( Zend_Registry::get('Zend_Controller_Plugin_ActionStack')) == 0)
		{
			//if user logs in, then layout will be changed to user's preference here

            //if the last request blocks which is not the block module
            //then add block/index/final to actionStack.
            //this action will render-to-Holder necessary blocks(menus, ads)
             
			// there are 2 cases where we do NOT want to invoke the /block/index/final action
			// 1. the last action is /block/index/final (otherwise it will cause endless loop)
			// 2. the controller ls 'block'. In this case, other modules are only 
			//    generating/returning a block of html, not the whole layout
			
			//TODO: no need for another actionStack here. Use the ActionMini
    		if ($this->_request->getControllerName() != 'block' && 
    			(! ($this->_request->getModuleName() == 'block' && $this->_request->getActionName() == 'final' && $this->_request->getControllerName() == 'index')))
        	{
      			$this->_helper->actionStack('final',
                                        	'index',
               	                            'block',
                   	                        array('lang' => 'en'));
            	$layout->currentPage = $this->_request->getModuleName(); //TODO: this might always be 'comment'
        	}
		} 
    }

    public function dispatchLoopShutdown(){}
    
    
    /* error handler for action that doesn't exist
	*/
    public function __call($method, $args)
    {
    	Zend_Registry::get('logger')->log("Action: " . $method, Zend_Log::INFO);
    	die($method . ' does not exists in class ' . get_class($this));
        return;
        // TODO: in deployment mode, forward to an error page
        if ('Action' == substr($method, -6)) {
            // If the action method was not found, render the error
            // template
            //return $this->render('error');
            die ("action <b>" . $method . "</b> for module <b>". $this->getRequest()->getModuleName() ."</b> does not exist <br/>");
        }

        // all other methods throw an exception
        throw new Exception('Invalid method "'
                            . $method
                            . '" called',
                            500);
    }

	/**
	 * $theme : not specified (default null) => commonTheme. Most used case
	 * 		  : true (Boolean) => use current Theme
	 * 		  : "prime" | "second" ...
	 */ 
    public function renderToHolder ($script, $useSessLang = false, $theme = null, $regionId = null, $weight = null)
    {
//    	die($script);
        $this->holderWeights = Zend_Registry::get('holderWeights');
        $sess = new Zend_Session_Namespace(CLU_NS);
        
        if (!$theme)
        	$theme = "commonTheme";
         //current viewed theme
        else
        {
        	if ($theme === true)
				$theme = isset($sess->userTheme) ? $sess->userTheme:Zend_Registry::get('configuration')->general->defaultTheme;
			/*        		
			else //specific theme
	    		$theme = $theme;
	    	*/
        }
        
    	if ($useSessLang)
        	$script = $theme.'/'.$sess->viewLang . '/' . $script;
    	else		
    		$script = $theme."/nolang/" . $script; /*todo: turn to 'nolang'*/
    		
//    	die($script);
        
        if (!$regionId)
        	$regionId = $this->regionId; //default
        if (!$weight)
        	$weight = $this->boxWeight;
        
        $i = $weight;		
        
        $name = 'region' . $regionId . '_box';
        while (array_key_exists($name.$i, $this->holderWeights))
        {
            $i++;
        }
        $placeholder = $name.$i;

        $this->view->placeholder($placeholder)->captureStart();
        echo $this->view->render($script);
        $this->view->placeholder($placeholder)->captureEnd();
        $this->holderWeights[$placeholder] = $weight; 
        Zend_Registry::set('holderWeights', $this->holderWeights);
        
    }
    
    public function setHolder ($content, $regionId = null, $weight = null )
    {
        $this->holderWeights = Zend_Registry::get('holderWeights');
    
    	//$script = Zend_Registry::get("viewLang") . '/' . $script;
        $i = $weight;
        
        $name = 'region' . $regionId . '_box';
        while (array_key_exists($name.$i, $this->holderWeights))
        {
            $i++;
        }
        $placeholder = $name.$i;
        $this->view->placeholder($placeholder)->captureStart();
        echo $content;
        $this->view->placeholder($placeholder)->captureEnd();
        $this->holderWeights[$placeholder] = $weight;
        Zend_Registry::set('holderWeights', $this->holderWeights);
        
    }
    
    /**
     *  This is an alternate to the costly addActionStack() of Zend Action Controller
     *  Basically it takes only a small amount of neccessary info in stead of the whole 
     *  heavy Action Controller's params like $request Object and shit...
     * 
     *  Should be able to access to view & the render property
     *  Also has theme,template ,region and weight params as well
     * 
     *  protected because it's only used internally. 
     *  something like /en/home/index/add-mini would not be a appropriate action
     */
    protected function addMiniAction($miniRequest)
    {
    	$module = $miniRequest['module'];
    	$controller = Ucwords($miniRequest['controller']); //Uppercase word
    	$action = $miniRequest['action'];
    	//$controller = $miniRequest['controller']; /* blockController in most cases*/
    	$sess = new Zend_Session_Namespace(CLU_NS);
    	$lang = $sess->viewLang;
    	// get the mini controller
    	$controllerClassName = Ucwords($module) . "_" . $controller . "Controller";//Home_GomeController

    	/*
    	set_include_path(  
            get_include_path() . PATH_SEPARATOR .  
            APP_PATH.'/modules/'.$module . '/controllers' 
        );
        */
    	require_once (APP_PATH.'/modules/'.$module . '/controllers/' . $controller . 'Controller.php');

    	//add the include path
		$miniRequest['view'] = $this->view;
    	$minController = new $controllerClassName($miniRequest);
    	$a = $action . "Action";
    	$minController->{$a}();
    }
    
    public function renderError($errorCode)
    {
    	$this->renderToHolder();
    }
    
    public function sendJsonError($errorCode, $errorMessage)
    {
    	$ret['success'] = false;
    	$ret['errorMessage'] = $errorMessage;
		if ($this->_request->isXmlHttpRequest())
			$this->_helper->json->sendJson($ret);
		exit();
    }
    
}
?>
